package k8s_ui

import (
	"context"
	"errors"
	"fmt"
	"github.com/wonderivan/logger"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"strings"
)

var PersistentVolumeClaim pvc

type pvc struct{}

// 定义persistentvolume列表的返回内容，Items是persistentvolume列表，Total为persistentvolume元素总数
// 先过滤，再拿total，再做分页
type PersistentVolumeClaimResp struct {
	Items []corev1.PersistentVolumeClaim `json:"items"`
	Total int                            `json:"total"`
}

// 创建persistentvolumee,接收persistentvolumeCreate对象
func (p *pvc) CreatePersistentVolumeClaim(Name string, Namespace string, AccessModes string, Storage string, StorageClassName *string) (err error) {
	modeStrings := strings.Split(AccessModes, ",")
	var accessModes []corev1.PersistentVolumeAccessMode
	for _, modeString := range modeStrings {
		switch modeString {
		case "ReadWriteOnce":
			accessModes = append(accessModes, corev1.ReadWriteOnce)
		case "ReadOnlyMany":
			accessModes = append(accessModes, corev1.ReadOnlyMany)
		case "ReadWriteMany":
			accessModes = append(accessModes, corev1.ReadWriteMany)
		default:
			fmt.Errorf("unknown access mode: %s", modeString)
		}
	}

	persistentvolumeclaim := &corev1.PersistentVolumeClaim{
		ObjectMeta: metav1.ObjectMeta{
			Name:      Name,
			Namespace: Namespace,
		},
		Spec: corev1.PersistentVolumeClaimSpec{
			AccessModes:      accessModes,
			StorageClassName: StorageClassName,
			Resources: corev1.ResourceRequirements{
				Requests: corev1.ResourceList{
					corev1.ResourceStorage: resource.MustParse(Storage),
				},
			},
		},
		Status: corev1.PersistentVolumeClaimStatus{},
	}

	_, err = K8s.ClientSet.CoreV1().PersistentVolumeClaims(Namespace).Create(context.TODO(), persistentvolumeclaim, metav1.CreateOptions{})
	if err != nil {
		logger.Error(errors.New("创建PersistentVolumeClaim失败, " + err.Error()))
		return errors.New("创建PersistentVolumeClaim失败, " + err.Error())
	}
	return nil
}

// 获取persistentvolumeCreate列表
func (p *pvc) GetPersistentVolumeClaim(filterName string, namespace string, limit, page int) (persistentvolumeclaimResp *PersistentVolumeClaimResp, err error) {
	//通过clintset获取persistentvolumeclaim完整列表
	persistentvolumeList, err := K8s.ClientSet.CoreV1().PersistentVolumeClaims(namespace).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		//logger是给自己看的，return是给用户看的
		logger.Error("获取persistentvolumeclaim列表失败", err)
		return nil, errors.New("获取persistentvolumeclaim列表失败" + err.Error())
	}

	//实例化DataSelector对象,取名selectableData
	selectableData := &DataSelector{
		GenericDataList: p.toCells(persistentvolumeList.Items),
		//过滤
		DataSelect: &DataSelectQuery{
			//过滤名称
			Filter: &FilterQuery{Name: filterName},
			//分页数量
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	//先过滤
	filtered := selectableData.Filter()
	//再拿Total
	total := len(filtered.GenericDataList)
	//再排序和分页
	data := filtered.Sort().Paginate()
	//再将DataCell切片数据转成原生persistentvolume切片
	persistentvolumes := p.fromCells(data.GenericDataList)
	//返回
	return &PersistentVolumeClaimResp{
		Items: persistentvolumes,
		Total: total,
	}, nil
}

// 获取persistentvolume详情
func (p *pvc) GetPersistentVolumeClaimDetail(FilterName string, Namespace string) (persistentvolumeclaims *corev1.PersistentVolumeClaim, err error) {
	persistentvolumeclaims, err =
		K8s.ClientSet.CoreV1().PersistentVolumeClaims(Namespace).Get(context.TODO(), FilterName,
			metav1.GetOptions{})
	if err != nil {
		logger.Error(errors.New("获取persistentvolumeclaim详情失败, " + err.Error()))
		return nil, errors.New("获取persistentvolumeclaim详情失败, " + err.Error())
	}
	return persistentvolumeclaims, nil
}

// 删除persistentvolume
func (p *pvc) DeletePersistentVolumeClaim(FilterName string, Namespace string) (err error) {
	err = K8s.ClientSet.CoreV1().PersistentVolumeClaims(Namespace).Delete(context.TODO(), FilterName, metav1.DeleteOptions{})
	if err != nil {
		logger.Error("删除persistentvolume失败," + err.Error())
		return errors.New("删除persistentvolume失败," + err.Error())
	}
	return nil
}

// 把pvcCell转成corev1 pvc
func (p *pvc) fromCells(cells []DataCell) []corev1.PersistentVolumeClaim {
	pvcs := make([]corev1.PersistentVolumeClaim, len(cells))
	for i := range cells {
		pvcs[i] = corev1.PersistentVolumeClaim(cells[i].(persistentvolumeclaimCell))
	}
	return pvcs
}

// 把corev1 pvc转成DataCell
func (p *pvc) toCells(std []corev1.PersistentVolumeClaim) []DataCell {
	cells := make([]DataCell, len(std))
	for i := range std {
		cells[i] = persistentvolumeclaimCell(std[i])
	}
	return cells
}
